package com.user;

import com.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "ChangePassword", urlPatterns = {"/ChangePassword"})
public class ChangePassword extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String password1 = req.getParameter("password1");  //旧密码
        String password2 = req.getParameter("password2");  //新密码
        String querySql = "select * from animalfile09_systemuser where UserID = ? and Password = ?";
        Connection con1 = JdbcUtils.getCon();
        try {
            PreparedStatement stat = con1.prepareStatement(querySql);
            stat.setString(1, id);
            stat.setString(2, password1);
            final ResultSet rs = stat.executeQuery();
            if (!rs.next()) {
                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().println("{\"msg\": \"旧密码错误\"}");
                return;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return;
        }
        String sql = "update animalfile09_systemuser set Password = ? where UserID = ?";
        Connection con = JdbcUtils.getCon();
        PreparedStatement stat = null;
        try {
            stat = con.prepareStatement(sql);
            stat.setString(1, password2);
            stat.setString(2, id);
            stat.executeUpdate();
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println("{\"msg\": \"OK\"}");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtils.close2(con, stat);
        }
    }

}
